<!--
 * @Descripttion: 组合新增商品时，规格的选择
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-30 21:29:17
 * @LastEditors: cxguo
 * @LastEditTime: 2020-12-24 21:54:07
 -->
<template>
  <div>
    <div class="clearfix">
      <div class="fl">
        <h3 style="display: inline-block">规格信息</h3>
        <el-checkbox
          v-model="dataObj.isEnableSpecs"
          true-label="1"
          false-label="0"
          border
        >开启多规格</el-checkbox>
      </div>
      <el-button class="fr" type="text" @click="btnSetupSpecs">规格设置</el-button>
    </div>
    <el-divider />
    <el-form
      ref="goodInfoForm"
      :model="dataObj"
      :label-position="'left'"
      label-width="60px"
    >
      <div v-if="dataObj.isEnableSpecs === '0'" class="w300 paddingTb20">
        <el-form-item label="规格:" prop="specs">
          <el-input v-model="dataObj.specs" />
        </el-form-item>
      </div>
      <div v-if="dataObj.isEnableSpecs === '1'" class="specs">
        <el-checkbox
          v-model="dataObj.isSyncData"
          border
          true-label="1"
          false-label="0"
          class="sync"
        >同步价格，期初库存，库存预警</el-checkbox>
        <el-form-item v-for="(specsObj,index) in specsData" :key="`${index}`" :label="`${specsObj.name}: `">
          <el-checkbox-group v-model="specsObj.valueData">
            <el-checkbox v-for="(item, cindex) in specsObj.children " :key="`${cindex}`" :label="item.name" />
          </el-checkbox-group>
        </el-form-item>
      </div>
    </el-form>
    <vxe-grid
      ref="table"
      class="grid"
      border
      resizable
      highlight-hover-row
      :edit-config="{trigger: 'click', mode: 'row'}"
      :columns="columnsData"
      :data="finalTableData"
    />
  </div>
</template>
<script>

import { oftenuse } from '@/libs/mixins'
import clonedeep from 'clonedeep'
import { specs } from '../mixins'
import { getGoodSkuCode } from '@/api/goods/goods-sku.js'
import barcodes from './barcodes'
import stocks from './stocks'
import PriceCell from './price-cell'
import XEUtils from 'xe-utils'

export default {
  name: 'GoodSpecs',
  // eslint-disable-next-line vue/no-unused-components
  components: { barcodes, stocks, PriceCell },
  mixins: [oftenuse, specs],
  props: {
    unitData: {
      type: Array,
      default: () => { return [] }
    },
    baseData: {
      type: Object,
      default: () => { return null }
    },
    storeData: {
      type: Array,
      default: () => { return [] }
    }
  },
  data() {
    return {
      specsData: [],
      dataObj: { isEnableSpecs: '0', isSyncData: '1', specs: ' ' },
      codeColumnsData: [
        { field: 'code',
          title: '商品编码', width: 160,
          cellRender: { name: 'ElInput', props: { size: 'mini' }}
        },
        { field: 'isEnable',
          title: '商品状态', width: 80,
          cellRender: { name: 'ElSwitch', props: { activeValue: '1',
            inactiveValue: '0', size: 'mini' }}
        }
      ],
      moreColumnsData: [
        { field: 'barcodes', title: '条形码', width: 140, align: 'center',
          slots: {
            default: ({ row, column }) => {
              const data = {
                props: { unitData: this.unitData },
                model: {
                  value: XEUtils.get(row, column.property),
                  callback(value) {
                    XEUtils.set(row, column.property, value)
                  }
                },
                on: {}
              }
              return [<barcodes {...data}></barcodes>]
            }
          }
        },
        { field: 'stocks', title: '期初库存', width: 120,
          slots: {
            default: ({ row, column }) => {
              const data = {
                props: { unitData: this.unitData, storeData: this.storeData },
                model: {
                  value: XEUtils.get(row, column.property),
                  callback(value) {
                    XEUtils.set(row, column.property, value)
                  }
                },
                on: {}
              }
              return [<stocks {...data}></stocks>]
            }
          }
        }
      ],
      finalTableData: [],
      skuCode: ''
    }
  },
  computed: {
    priceColumns: function() {
      const priceTypes = this.getPriceType()
      return priceTypes.map(item => {
        const { value, label } = item
        return { field: value, title: label, width: 100, align: 'left',
          slots: {
            default: ({ row, column }) => {
              // eslint-disable-next-line no-unused-vars
              const h = this.$createElement
              const data = {
                props: { unitData: this.unitData },
                model: {
                  value: XEUtils.get(row, column.property),
                  callback(value) {
                    XEUtils.set(row, column.property, value)
                  }
                }
              }
              return [<PriceCell {...data}></PriceCell>]
            }
          }
        }
      })
    },
    /**
     * 显示的列数据
     */
    columnsData: function() {
      const codeColumnsData = this.codeColumnsData
      const moreColumnsData = this.moreColumnsData
      const specsColumns = this.specsColumns
      const priceColumns = this.priceColumns
      return [...specsColumns, ...codeColumnsData, ...priceColumns, ...moreColumnsData]
    },
    /**
     * 最终表格的数据
     */
    _finalTableData() {
      const spTableData = clonedeep(this.spTableData)
      const priceData = this.getPriceBlankData()
      if (!this.skuCode) return []
      spTableData.forEach((item, index) => {
        const name = this.getGoodName(item)
        item.specs = JSON.stringify(item)
        item.name = name
        item.code = this.getOneSkuCode(this.skuCode, index)
        item.isEnableSpecs = this.dataObj.isEnableSpecs
        item.barcodes = []
        item.stocks = []
        item.levels = []
        item.isEnable = '1'
        Object.keys(priceData).forEach(key => {
          item[key] = priceData[key]
        })
      })
      return spTableData
    },
    /**
     * 选中的规格
     */
    selectSpecsData: function() {
      if (this.dataObj.isEnableSpecs === '1') {
        const specsData = this.specsData
        const hasValueSpecs = specsData.filter(item => { return item.valueData && item.valueData.length > 0 })
        const result = []
        hasValueSpecs.forEach(item => {
          const { id } = item
          const obj = {}
          const key = id
          obj[key] = item.valueData
          result.push(obj)
        })
        return result
      }
      const specsValue = this.dataObj.specs
      if (specsValue) return [{ '默认': [specsValue] }]
      return []
    }
  },
  watch: {
    '_finalTableData': {
      handler(data) {
        this.finalTableData = data
      },
      deep: true
    }
  },
  created() {
    this.getSkuCode()
    this.getSpecsSelectData()
  },
  methods: {
    btnSetupSpecs() {
      this.$router.push({ name: 'SpecsList' })
    },
    btnEditMore(row) {
      this.$emit('on-sku-edit', row)
    },
    // export api
    /**
     * 最终表格里所有的数据
     */
    getSpTableData() {
      const data = this.$refs.table.getTableData().fullData
      data.forEach(item => {
        if (item.isEnableSpecs === '0') {
          const specsObj = JSON.parse(item.specs || '{}')
          item.specs = specsObj['默认']
          item.priceListData = this.getPriceListData(item)
        }
      })
      return data
    },
    getPriceListData(row) {
      const priceListData = []
      const unitData = this.unitData
      unitData.forEach(item => {
        const obj = {}
        const unitId = item.value
        obj.unitId = unitId
        obj.price = this.getPriceStrByUnitId(unitId, row)
        priceListData.push(obj)
      })
      return priceListData
    },
    getPriceStrByUnitId(unitId, row) {
      const priceType = this.getPriceType()
      const priceKeys = priceType.map(item => { return item.value })
      const priceObj = {}
      Object.keys(row).forEach(key => {
        if (priceKeys.indexOf(key) !== -1) {
          const unitPrices = row[key] || []
          const unitPrice = unitPrices.find(item => { return item.unitId === unitId })
          if (unitPrice) {
            priceObj[key] = unitPrice['price']
          } else {
            priceObj[key] = this.$amount(0).format()
          }
        }
      })
      return JSON.stringify(priceObj)
    },
    valiData() {
      const selectSpecsData = this.selectSpecsData
      const that = this
      return new Promise((resolve, reject) => {
        if (selectSpecsData.length) {
          resolve()
        } else {
          const MSG = '至少选择一个规格！'
          that.$message.error(MSG)
          reject(new Error(MSG))
        }
      })
    },
    getGoodName(specsRow) {
      const goodName = this.baseData.name
      return goodName
    },
    /**
     * 获取Sku编码
     */
    getSkuCode() {
      getGoodSkuCode().then(res => {
        console.log('获取code', res.data.data)
        if (!res.data.flag) return this.$message.error('获取sku编码失败！')
        this.skuCode = res.data.data
      })
    },
    getOneSkuCode(initCode, index) {
      const initCodeNum = initCode.match(/\d+/g).join('')
      const perfix = initCode.replace(initCodeNum, '')
      return `${perfix}${Number(initCodeNum) + index}`
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-divider--horizontal{
    margin: 5px 0;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom: 10px;
  }
  .specs{
    position: relative;
    .sync{
      position: absolute; right: 0; bottom:10px; z-index: 10;
    }
  }
</style>
